<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; frame-src 'self' https://www.liwenyan.site">
    
    <!-- 禁止使用opener -->
    <meta name="referrer" content="no-referrer">
    
    <!-- 禁止弹出窗口 -->
    <meta http-equiv="Window-Target" content="_top">
    
    <!-- 添加noopener noreferrer到所有链接 -->
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        // 禁止window.open
        window.open = function() { return null; };
        
        // 在顶级文档上禁止弹出窗口
        if (window.top === window) {
          window.open = function() { return null; };
        }
      });
    </script>
    <style>
      /* 基础样式 */
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      
      :root {
        --titlebar-bg: #0d4ca4;
        --titlebar-text: #ffffff;
        --titlebar-hover: rgba(255, 255, 255, 0.2);
        --titlebar-close-hover: #e74c3c;
        --content-bg: #f0f5fa;
        --btn-text: #ffffff;
        --btn-icon-fill: #ffffff;
        --toast-bg: rgba(0, 0, 0, 0.8);
        --toast-text: #ffffff;
        --toast-success: rgba(39, 174, 96, 0.9);
        --toast-error: rgba(231, 76, 60, 0.9);
        --toast-info: rgba(52, 152, 219, 0.9);
        --toast-warning: rgba(243, 156, 18, 0.9);
      }
      
      /* 暗色主题 */
      [data-theme="dark"] {
        --titlebar-bg: #1a1a1a;
        --titlebar-text: #ffffff;
        --titlebar-hover: rgba(255, 255, 255, 0.1);
        --titlebar-close-hover: #e74c3c;
        --content-bg: #2d2d2d;
        --btn-text: #ffffff;
        --btn-icon-fill: #ffffff;
      }
      
      /* 浅色主题 */
      [data-theme="light"] {
        --titlebar-bg: #f0f0f0;
        --titlebar-text: #333333;
        --titlebar-hover: rgba(0, 0, 0, 0.1);
        --titlebar-close-hover: #e74c3c;
        --content-bg: #ffffff;
        --btn-text: #333333;
        --btn-icon-fill: #333333;
      }
      
      /* 蓝色主题 */
      [data-theme="blue"] {
        --titlebar-bg: #3498db;
        --titlebar-text: #ffffff;
        --titlebar-hover: rgba(255, 255, 255, 0.2);
        --titlebar-close-hover: #e74c3c;
        --content-bg: #ecf0f1;
        --btn-text: #ffffff;
        --btn-icon-fill: #ffffff;
      }
      
      body {
        font-family: Arial, sans-serif;
        display: flex;
        flex-direction: column;
        height: 100vh;
        overflow: hidden;
        background-color: var(--content-bg);
      }
      
      /* 标题栏样式 */
      .titlebar {
        height: 40px;
        background-color: var(--titlebar-bg);
        display: flex;
        align-items: center;
        -webkit-app-region: drag;
        color: var(--titlebar-text);
        z-index: 100;
      }
      
      .title {
        font-weight: bold;
        font-size: 14px;
        margin-left: 20px;
      }
      
      .titlebar-buttons {
        display: flex;
        align-items: center;
        margin-left: auto;
        padding-right: 8px;
        -webkit-app-region: no-drag;
      }
      
      .btn {
        background: none;
        border: none;
        color: var(--btn-text);
        height: 40px;
        padding: 0 12px;
        font-size: 16px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        -webkit-app-region: no-drag;
      }
      
      .btn:hover {
        background-color: var(--titlebar-hover);
      }
      
      .icon-btn {
        background: none;
        border: none;
        color: var(--btn-text);
        height: 40px;
        width: 40px;
        font-size: 16px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        -webkit-app-region: no-drag;
        opacity: 0.85;
        transition: opacity 0.2s;
      }
      
      .icon-btn:hover {
        opacity: 1;
        background-color: var(--titlebar-hover);
      }
      
      .icon-btn.loading {
        animation: spin 1s linear infinite;
        pointer-events: none;
      }
      
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      
      #cache-btn:hover, #refresh-btn:hover, #theme-btn:hover, #update-btn:hover {
        background-color: var(--titlebar-hover);
      }
      
      #close-btn:hover {
        background-color: var(--titlebar-close-hover);
      }
      
      /* 主题选择菜单 */
      .theme-dropdown {
        position: relative;
        display: inline-block;
      }
      
      .theme-menu {
        display: none;
        position: absolute;
        top: 40px;
        right: 0;
        background-color: var(--titlebar-bg);
        min-width: 120px;
        box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        z-index: 1000;
        border-radius: 4px;
        overflow: hidden;
      }
      
      .theme-menu.show {
        display: block;
      }
      
      .theme-item {
        color: var(--titlebar-text);
        padding: 10px 12px;
        text-decoration: none;
        display: block;
        cursor: pointer;
        font-size: 14px;
        text-align: left;
        border: none;
        width: 100%;
        background: none;
      }
      
      .theme-item:hover {
        background-color: var(--titlebar-hover);
      }
      
      .theme-item.active {
        font-weight: bold;
        background-color: var(--titlebar-hover);
      }
      
      /* 内容区域样式 */
      .content {
        flex: 1;
        position: relative;
        background-color: var(--content-bg);
      }
      
      webview {
        width: 100%;
        height: 100%;
        border: none;
      }
      
      /* Toast通知样式 */
      .toast-container {
        position: fixed;
        top: 60px;
        right: 20px;
        z-index: 9999;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
      }
      
      .toast {
        min-width: 250px;
        max-width: 400px;
        background-color: var(--toast-bg);
        color: var(--toast-text);
        padding: 12px 16px;
        margin-bottom: 10px;
        border-radius: 4px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        display: flex;
        align-items: center;
        animation: toast-in 0.3s ease-out;
        overflow: hidden;
      }
      
      .toast.info {
        background-color: var(--toast-info);
      }
      
      .toast.success {
        background-color: var(--toast-success);
      }
      
      .toast.error {
        background-color: var(--toast-error);
      }
      
      .toast.warning {
        background-color: var(--toast-warning);
      }
      
      .toast-icon {
        margin-right: 12px;
        flex-shrink: 0;
      }
      
      .toast-content {
        flex-grow: 1;
      }
      
      .toast-close {
        margin-left: 12px;
        cursor: pointer;
        opacity: 0.7;
        transition: opacity 0.2s;
        flex-shrink: 0;
      }
      
      .toast-close:hover {
        opacity: 1;
      }
      
      .toast-progress {
        position: absolute;
        bottom: 0;
        left: 0;
        height: 3px;
        background-color: rgba(255, 255, 255, 0.5);
      }
      
      @keyframes toast-in {
        from {
          transform: translateX(100%);
          opacity: 0;
        }
        to {
          transform: translateX(0);
          opacity: 1;
        }
      }
      
      @keyframes toast-out {
        from {
          transform: translateX(0);
          opacity: 1;
        }
        to {
          transform: translateX(100%);
          opacity: 0;
        }
      }
      
      .toast.toast-out {
        animation: toast-out 0.3s ease-in forwards;
      }
      
      /* 自定义对话框样式 */
    </style>
    <title>管理系统</title>
  </head>
  <body>
    <!-- 标题栏 -->
    <div class="titlebar">
      <div class="title">管理系统</div>
      <div class="titlebar-buttons">
        <button id="refresh-btn" class="icon-btn" onclick="handleRefresh()" title="刷新页面">
          <svg width="16" height="16" viewBox="0 0 24 24">
            <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" fill="currentColor"/>
          </svg>
        </button>
        <button id="cache-btn" class="icon-btn" onclick="handleClearCache()" title="清除缓存">
          <svg width="16" height="16" viewBox="0 0 24 24">
            <path d="M15 4V3H9v1H4v2h1v13c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V6h1V4h-5zm2 15H7V6h10v13zM9 8h2v9H9zm4 0h2v9h-2z" fill="currentColor"/>
          </svg>
        </button>
        <!-- 主题切换按钮 -->
        <div class="theme-dropdown">
          <button id="theme-btn" class="icon-btn" onclick="toggleThemeMenu()" title="切换主题">
            <svg width="16" height="16" viewBox="0 0 24 24">
              <path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9-4.03-9-9-9zm0 16c-3.86 0-7-3.14-7-7s3.14-7 7-7 7 3.14 7 7-3.14 7-7 7z" fill="currentColor"/>
              <path d="M12 5v14c3.86 0 7-3.14 7-7s-3.14-7-7-7z" fill="currentColor"/>
            </svg>
          </button>
          <div id="theme-menu" class="theme-menu">
            <button class="theme-item" data-theme="default" onclick="changeTheme('default')">蓝色主题</button>
            <button class="theme-item" data-theme="dark" onclick="changeTheme('dark')">暗色主题</button>
            <button class="theme-item" data-theme="light" onclick="changeTheme('light')">浅色主题</button>
            <button class="theme-item" data-theme="blue" onclick="changeTheme('blue')">浅蓝主题</button>
            <hr style="border: none; border-top: 1px solid var(--titlebar-hover); margin: 4px 0;">
            <button class="theme-item" id="system-theme-toggle" onclick="toggleSystemTheme()">跟随系统主题</button>
          </div>
        </div>
        <button id="min-btn" class="btn" onclick="window.electronAPI.minimizeWindow()">&#8211;</button>
        <button id="max-btn" class="btn" onclick="window.electronAPI.maximizeWindow()">□</button>
        <button id="close-btn" class="btn" onclick="window.electronAPI.closeWindow()">✕</button>
        <!-- 添加检查更新按钮 -->
        <button id="update-btn" class="icon-btn" title="检查更新" style="display: none;">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21 2v6h-6"></path>
            <path d="M3 12a9 9 0 0 1 15-6.7L21 8"></path>
            <path d="M3 22v-6h6"></path>
            <path d="M21 12a9 9 0 0 1-15 6.7L3 16"></path>
          </svg>
        </button>
      </div>
    </div>
    
    <!-- 内容区域 - 单一webview -->
    <div class="content" id="content">
      <webview id="mainWebview" src="https://www.liwenyan.site/doc" allowpopups="false" 
               partition="persist:webcontent" 
               disableblinkfeatures="Auxclick,PopupBlockerTab" 
               preload="./preload.js"
               webpreferences="nativeWindowOpen=false, nodeIntegration=false, contextIsolation=true, nodeIntegrationInSubFrames=false"
               disableguestresize="true"
               disablewebsecurity="false">
      </webview>
      
      <!-- 更新进度条覆盖层 -->
      <div id="update-progress-overlay" style="display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.75); z-index: 1000; flex-direction: column; justify-content: center; align-items: center; color: white; padding: 20px; backdrop-filter: blur(5px); opacity: 0; transition: opacity 0.3s ease;">
        <div style="background: rgba(30, 30, 30, 0.9); width: 90%; max-width: 450px; border-radius: 12px; padding: 25px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3); border: 1px solid rgba(255, 255, 255, 0.1); text-align: center; transform: translateY(0); transition: transform 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);">
          <div id="update-icon" style="margin: 0 auto 15px auto; width: 60px; height: 60px; background: linear-gradient(135deg, #4776e6, #8e54e9); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
            <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M21 2v6h-6"></path>
              <path d="M3 12a9 9 0 0 1 15-6.7L21 8"></path>
              <path d="M3 22v-6h6"></path>
              <path d="M21 12a9 9 0 0 1-15 6.7L3 16"></path>
            </svg>
          </div>
          <h3 id="update-title" style="margin: 0 0 15px 0; font-size: 22px; font-weight: 500; text-align: center; color: #fff;">发现新版本</h3>
          <div id="update-status" style="font-size: 16px; margin: 10px 0 20px 0; color: rgba(255, 255, 255, 0.8); text-align: center; line-height: 1.5;">有新版本可用，请更新</div>
          
          <!-- 下载更新过程中显示的进度条 -->
          <div id="progress-container" style="margin: 25px 0; position: relative; display: none;">
            <div style="width: 100%; height: 8px; background: rgba(255, 255, 255, 0.1); border-radius: 4px; overflow: hidden; position: relative;">
              <div id="progress-bar-inner" style="position: absolute; left: 0; top: 0; height: 100%; width: 0%; background: linear-gradient(90deg, #4776e6, #8e54e9); border-radius: 4px; transition: width 0.3s ease;"></div>
            </div>
            <div id="progress-text" style="font-size: 14px; margin-top: 12px; color: rgba(255, 255, 255, 0.7); text-align: center;">准备下载...</div>
          </div>
          
          <progress id="update-progress-bar" value="0" max="100" style="display: none;"></progress>
          
          <!-- 用于检查更新时的按钮 -->
          <div id="update-buttons" style="display: flex; justify-content: center; margin-top: 5px;">
            <button id="update-confirm-btn" style="background: linear-gradient(90deg, #4776e6, #8e54e9); border: none; color: white; padding: 10px 20px; border-radius: 6px; font-size: 15px; cursor: pointer; transition: all 0.2s; margin: 0 6px;">立即更新</button>
            <button id="update-later-btn" style="background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); color: white; padding: 10px 20px; border-radius: 6px; font-size: 15px; cursor: pointer; transition: all 0.2s; margin: 0 6px;">稍后更新</button>
          </div>
        </div>
      </div>
      
      <!-- 自定义对话框覆盖层 -->
      <div id="custom-dialog-overlay" style="display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.75); z-index: 2000; flex-direction: column; justify-content: center; align-items: center; color: white; padding: 20px; backdrop-filter: blur(5px); opacity: 0; transition: opacity 0.3s ease;">
        <div id="custom-dialog-container" style="background: rgba(30, 30, 30, 0.9); width: 90%; max-width: 450px; border-radius: 12px; padding: 25px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3); border: 1px solid rgba(255, 255, 255, 0.1); text-align: center; transform: translateY(0); transition: transform 0.3s cubic-bezier(0.18, 0.89, 0.32, 1.28);">
          <div id="dialog-icon" style="margin: 0 auto 15px auto; width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
            <!-- 图标将根据对话框类型动态设置 -->
          </div>
          <h3 id="dialog-title" style="margin: 0 0 15px 0; font-size: 22px; font-weight: 500; text-align: center; color: #fff;">对话框标题</h3>
          <div id="dialog-message" style="font-size: 16px; margin: 10px 0 25px 0; color: rgba(255, 255, 255, 0.8); text-align: center; line-height: 1.5;">对话框消息内容</div>
          
          <!-- 对话框按钮容器 -->
          <div id="dialog-buttons" style="display: flex; justify-content: center; margin-top: 5px;">
            <!-- 按钮将根据对话框选项动态生成 -->
          </div>
        </div>
      </div>
    </div>

    <script>
      let mainWebview;
      let currentTheme = "default";
      
      // 切换是否跟随系统主题
      function toggleSystemTheme() {
        const systemThemeBtn = document.getElementById('system-theme-toggle');
        const currentValue = localStorage.getItem('theme-follows-system') === 'true';
        const newValue = !currentValue;
        
        // 保存设置
        localStorage.setItem('theme-follows-system', newValue);
        
        // 更新按钮状态
        if (systemThemeBtn) {
          if (newValue) {
            systemThemeBtn.classList.add('active');
            systemThemeBtn.textContent = '✓ 跟随系统主题';
            
            // 立即应用系统主题
            if (window.electronAPI && window.electronAPI.getSystemTheme) {
              const systemTheme = window.electronAPI.getSystemTheme();
              changeTheme(systemTheme === 'dark' ? 'dark' : 'light');
            }
          } else {
            systemThemeBtn.classList.remove('active');
            systemThemeBtn.textContent = '跟随系统主题';
          }
        }
        
        // 关闭主题菜单
        const themeMenu = document.getElementById('theme-menu');
        if (themeMenu) {
          themeMenu.classList.remove('show');
        }
      }
      
      // 初始化主题
      function initTheme() {
        // 尝试从localStorage获取保存的主题
        const savedTheme = localStorage.getItem('app-theme') || 'default';
        const followsSystem = localStorage.getItem('theme-follows-system') === 'true';
        
        // 初始化跟随系统主题按钮
        const systemThemeBtn = document.getElementById('system-theme-toggle');
        if (systemThemeBtn) {
          if (followsSystem) {
            systemThemeBtn.classList.add('active');
            systemThemeBtn.textContent = '✓ 跟随系统主题';
            
            // 如果跟随系统主题，则应用系统主题
            if (window.electronAPI && window.electronAPI.getSystemTheme) {
              const systemTheme = window.electronAPI.getSystemTheme();
              changeTheme(systemTheme === 'dark' ? 'dark' : 'light', false);
            } else {
              changeTheme(savedTheme, false);
            }
          } else {
            systemThemeBtn.classList.remove('active');
            systemThemeBtn.textContent = '跟随系统主题';
            changeTheme(savedTheme, false);
          }
        } else {
          changeTheme(savedTheme, false);
        }
        
        // 关闭主题菜单（点击其他区域）
        document.addEventListener('click', function(event) {
          const themeBtn = document.getElementById('theme-btn');
          const themeMenu = document.getElementById('theme-menu');
          if (themeMenu && themeBtn && !themeBtn.contains(event.target) && !themeMenu.contains(event.target)) {
            themeMenu.classList.remove('show');
          }
        });
      }
      
      // 切换主题菜单显示/隐藏
      function toggleThemeMenu() {
        const themeMenu = document.getElementById('theme-menu');
        themeMenu.classList.toggle('show');
        
        // 更新当前选中的主题
        const themeItems = document.querySelectorAll('.theme-item');
        themeItems.forEach(item => {
          if (item.getAttribute('data-theme') === currentTheme) {
            item.classList.add('active');
          } else {
            item.classList.remove('active');
          }
        });
      }
      
      // 切换主题
      function changeTheme(theme, saveToStorage = true) {
        // 保存当前主题
        currentTheme = theme;
        
        // 清除现有主题
        document.body.removeAttribute('data-theme');
        
        // 设置新主题
        if (theme !== 'default') {
          document.body.setAttribute('data-theme', theme);
        }
        
        // 保存主题到localStorage
        if (saveToStorage) {
          localStorage.setItem('app-theme', theme);
          
          // 关闭主题菜单
          const themeMenu = document.getElementById('theme-menu');
          if (themeMenu) {
            themeMenu.classList.remove('show');
          }
        }
        
        // 如果webview内容已加载，则向webview发送主题改变消息
        if (mainWebview && mainWebview.getURL()) {
          try {
            mainWebview.executeJavaScript(`
              // 通知网页主题已改变
              document.documentElement.setAttribute('data-app-theme', '${theme}');
              // 发出自定义事件
              document.dispatchEvent(new CustomEvent('app-theme-changed', { detail: { theme: '${theme}' } }));
            `).catch(err => console.warn('无法向webview设置主题:', err));
          } catch (e) {
            console.warn('无法向webview设置主题:', e);
          }
        }
      }
      
      // 刷新当前页面
      function handleRefresh() {
        console.log('刷新按钮被点击');
        try {
          // 获取按钮元素并添加加载样式
          const refreshBtn = document.getElementById('refresh-btn');
          if (refreshBtn) {
            refreshBtn.classList.add('loading');
          }
          
          // 刷新webview
          if (mainWebview) {
            mainWebview.reload();
            console.log('页面已刷新');
            
            // 刷新完成后移除加载样式
            mainWebview.addEventListener('did-finish-load', () => {
              if (refreshBtn) {
                refreshBtn.classList.remove('loading');
              }
            }, { once: true });
            
            // 如果加载超时或失败，也移除加载样式
            setTimeout(() => {
              if (refreshBtn) {
                refreshBtn.classList.remove('loading');
              }
            }, 5000);
          } else {
            console.error('未找到webview');
            if (refreshBtn) {
              refreshBtn.classList.remove('loading');
            }
          }
        } catch (err) {
          console.error('刷新页面失败:', err);
          // 移除加载样式
          const refreshBtn = document.getElementById('refresh-btn');
          if (refreshBtn) {
            refreshBtn.classList.remove('loading');
          }
        }
      }
      
      // 清除缓存
      function handleClearCache() {
        console.log('清除缓存按钮被点击');
        try {
          // 显示一个简单的加载指示器
          const cacheBtn = document.getElementById('cache-btn');
          if (cacheBtn) {
            cacheBtn.classList.add('loading');
            cacheBtn.setAttribute('disabled', 'true');
          }
          
          // 使用提供的原生方法清除缓存
          if (window.electronAPI && window.electronAPI.menuClearCache) {
            window.electronAPI.menuClearCache()
              .then(result => {
                console.log('缓存清除结果:', result);
              })
              .catch(err => {
                console.error('缓存清除失败:', err);
              })
              .finally(() => {
                // 清理按钮状态
                if (cacheBtn) {
                  setTimeout(() => {
                    cacheBtn.classList.remove('loading');
                    cacheBtn.removeAttribute('disabled');
                  }, 500);
                }
              });
          } else {
            console.error('无法清除缓存：menuClearCache 方法不存在');
            if (cacheBtn) {
              cacheBtn.classList.remove('loading');
              cacheBtn.removeAttribute('disabled');
            }
          }
        } catch (err) {
          console.error('调用清除缓存失败:', err);
          const cacheBtn = document.getElementById('cache-btn');
          if (cacheBtn) {
            cacheBtn.classList.remove('loading');
            cacheBtn.removeAttribute('disabled');
          }
        }
      }

      // DOM加载完成后设置消息监听
      document.addEventListener('DOMContentLoaded', () => {
        console.log('DOM元素已加载');
        
        // 初始化主题
        initTheme();
        
        // 监听系统主题变化（可选功能）
        if (window.electronAPI && window.electronAPI.onSystemThemeChange) {
          window.electronAPI.onSystemThemeChange((systemTheme) => {
            console.log('系统主题变化检测到:', systemTheme);
            // 如果用户选择了跟随系统主题，则自动切换
            if (localStorage.getItem('theme-follows-system') === 'true') {
              changeTheme(systemTheme === 'dark' ? 'dark' : 'light');
            }
          });
        }
        
        // 获取主webview引用
        mainWebview = document.getElementById('mainWebview');
        
        // 设置webview事件处理
        if (mainWebview) {
          mainWebview.addEventListener('dom-ready', () => {
            console.log('Webview DOM已就绪');
            setupWebViewHandlers(mainWebview);
            
            // 向webview应用当前主题
            if (currentTheme) {
              try {
                mainWebview.executeJavaScript(`
                  // 通知网页当前主题
                  document.documentElement.setAttribute('data-app-theme', '${currentTheme}');
                `).catch(err => console.warn('无法向webview设置初始主题:', err));
              } catch (e) {
                console.warn('无法向webview设置初始主题:', e);
              }
            }
          });
          
          // 更新页面标题
          mainWebview.addEventListener('page-title-updated', (e) => {
            document.title = e.title || '管理系统';
          });
        }
        
        // 监听来自主进程的重新加载消息
        if (window.electronAPI && window.electronAPI.onReloadWebview) {
          window.electronAPI.onReloadWebview(() => {
            console.log('收到重新加载webview的消息');
            if (mainWebview) {
              mainWebview.reload();
            }
          });
        }
        
        // 添加window消息监听器，处理来自webview的消息
        window.addEventListener('message', (event) => {
          console.log('收到window消息:', event.data);
          if (event.data && event.data.type === 'createNewTab' && event.data.url) {
            console.log('收到URL:', event.data.url);
            // 直接在当前webview中加载URL，而不是创建新标签
            if (mainWebview) {
              mainWebview.src = event.data.url;
            }
          } else if (event.data && event.data.type === 'openExternal' && event.data.url) {
            console.log('收到打开外部链接的请求:', event.data.url);
            // 使用默认浏览器打开外部链接
            window.electronAPI.openExternal(event.data.url);
          }
        });
      });
      
      // 设置webview的事件处理函数
      function setupWebViewHandlers(webview) {
        // 拦截新窗口请求，直接在当前webview中加载
        webview.addEventListener('new-window', (e) => {
          console.log('拦截到new-window事件:', e.url);
          e.preventDefault();
          if (webview) {
            webview.src = e.url;
          }
        });
        
        // 监听webview内的导航变化
        webview.addEventListener('will-navigate', (e) => {
          console.log('将要导航到:', e.url);
        });
        
        // 注入脚本以拦截所有target="_blank"链接
        webview.executeJavaScript(`
          (function() {
            // 立即捕获并重写当前窗口创建相关功能
            console.log('开始注入链接拦截脚本');
            
            // 判断是否为内部链接
            function isInternalLink(url) {
              if (!url) return false;
              try {
                const urlObj = new URL(url);
                // 检查是否是当前域名或特定域名
                return urlObj.hostname === 'www.liwenyan.site' || 
                       urlObj.hostname.endsWith('.liwenyan.site');
              } catch (e) {
                // 如果无法解析URL，假设是外部链接
                return false;
              }
            }
            
            // 1. 禁用所有可能创建新窗口的方法
            window.open = function(url) { 
              console.log('拦截window.open:', url);
              if (url) {
                if (isInternalLink(url)) {
                  // 内部链接在当前页面打开
                  console.log('内部链接，在当前页面加载:', url);
                  setTimeout(() => {
                    window.location.href = url;
                  }, 0);
                } else {
                  // 外部链接使用默认浏览器打开
                  console.log('外部链接，使用默认浏览器打开:', url);
                  if (window.electron) {
                    window.electron.openExternal(url);
                  } else {
                    // 发送消息到外层
                    window.postMessage({
                      type: 'openExternal',
                      url: url
                    }, '*');
                  }
                }
              }
              return null; 
            };
            
            // 防止通过原型链调用window.open
            try {
              Object.defineProperty(window, 'open', {
                configurable: false,
                writable: false,
                value: function(url) { 
                  console.log('拦截Object.defineProperty window.open:', url);
                  if (url) {
                    if (isInternalLink(url)) {
                      setTimeout(() => {
                        window.location.href = url;
                      }, 0);
                    } else {
                      // 外部链接使用默认浏览器打开
                      if (window.electron) {
                        window.electron.openExternal(url);
                      } else {
                        window.postMessage({
                          type: 'openExternal',
                          url: url
                        }, '*');
                      }
                    }
                  }
                  return null; 
                }
              });
            } catch(e) {
              console.warn('无法完全锁定window.open:', e);
            }
            
            // 2. 禁用其他可能创建窗口的方法
            if (window.showModalDialog) window.showModalDialog = function() { return null; };
            if (window.showModelessDialog) window.showModelessDialog = function() { return null; };
            
            // 3. 阻止window.open相关功能
            try {
              // 覆盖Window.prototype.open
              Window.prototype.open = function(url) { 
                console.log('拦截Window.prototype.open:', url); 
                if (url) {
                  if (isInternalLink(url)) {
                    setTimeout(() => {
                      window.location.href = url;
                    }, 0);
                  } else {
                    // 外部链接使用默认浏览器打开
                    if (window.electron) {
                      window.electron.openExternal(url);
                    } else {
                      window.postMessage({
                        type: 'openExternal',
                        url: url
                      }, '*');
                    }
                  }
                }
                return null; 
              };
            } catch(e) {
              console.warn('无法修改Window.prototype.open:', e);
            }
            
            // 4. 修改所有target="_blank"链接，根据URL决定打开方式
            function modifyExternalLinks() {
              try {
                // 查找所有新窗口链接
                const links = document.querySelectorAll('a[target="_blank"], a[target="_new"], a[target="blank"], a[target="new"], a[rel~="noopener"], a[rel~="noreferrer"]');
                
                links.forEach(function(link) {
                  // 保存原始URL
                  const href = link.getAttribute('href');
                  if (!href) return;
                  
                  // 在链接上设置一个特殊标记，表示已处理
                  if (link.hasAttribute('data-electron-processed')) return;
                  link.setAttribute('data-electron-processed', 'true');
                  
                  // 覆盖点击事件
                  link.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    console.log('拦截链接点击:', href);
                    
                    if (isInternalLink(href)) {
                      // 内部链接在当前页面打开
                      window.location.href = href;
                    } else {
                      // 外部链接使用默认浏览器打开
                      if (window.electron) {
                        window.electron.openExternal(href);
                      } else {
                        window.postMessage({
                          type: 'openExternal',
                          url: href
                        }, '*');
                      }
                    }
                    
                    return false;
                  }, true);
                  
                  // 如果是内部链接，保留原本行为，让它能在当前页面打开
                  if (isInternalLink(href)) {
                    link.removeAttribute('target');
                  }
                });
                
                console.log('修改了' + links.length + '个目标链接');
              } catch (err) {
                console.error('修改链接失败:', err);
              }
            }
            
            // 立即运行一次
            modifyExternalLinks();
            
            // 监听DOM变化以处理动态添加的链接
            try {
              const observer = new MutationObserver(function(mutations) {
                modifyExternalLinks();
              });
              
              observer.observe(document.documentElement, {
                childList: true,
                subtree: true,
                attributes: true,
                attributeFilter: ['target', 'href', 'rel']
              });
              
              console.log('已设置DOM观察器');
            } catch(e) {
              console.warn('无法设置DOM观察器:', e);
              
              // 备用方案：定期检查
              setInterval(modifyExternalLinks, 1000);
            }
            
            // 处理iframe
            function processIframes() {
              try {
                const iframes = document.querySelectorAll('iframe');
                iframes.forEach(function(iframe) {
                  if (iframe.hasAttribute('data-electron-processed')) return;
                  iframe.setAttribute('data-electron-processed', 'true');
                  
                  // 监听iframe加载完成
                  iframe.onload = function() {
                    try {
                      // 尝试访问iframe内容
                      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                      const iframeWin = iframe.contentWindow;
                      
                      // 禁用iframe中的window.open
                      if (iframeWin) {
                        try {
                          iframeWin.open = function(url) { 
                            if (!url) return null;
                            
                            if (isInternalLink(url)) {
                              window.location.href = url;
                            } else {
                              // 外部链接使用默认浏览器打开
                              if (window.electron) {
                                window.electron.openExternal(url);
                              } else {
                                window.postMessage({
                                  type: 'openExternal',
                                  url: url
                                }, '*');
                              }
                            }
                            return null; 
                          };
                        } catch(e) {
                          console.warn('无法覆盖iframe window.open:', e);
                        }
                      }
                    } catch(e) {
                      console.error('处理iframe失败:', e);
                    }
                  };
                });
              } catch(e) {
                console.error('处理所有iframe失败:', e);
              }
            }
            
            // 运行一次iframe处理
            processIframes();
            
            // 监听iframe变化
            try {
              const iframeObserver = new MutationObserver(function(mutations) {
                processIframes();
              });
              
              iframeObserver.observe(document.documentElement, {
                childList: true,
                subtree: true
              });
            } catch(e) {
              console.warn('无法设置iframe观察器:', e);
              setInterval(processIframes, 2000);
            }
            
            console.log('完成链接拦截脚本注入');
          })();
        `).catch(err => {
          console.error('注入JavaScript失败:', err);
        });
        
        // 监听来自webview的消息
        webview.addEventListener('console-message', (e) => {
          console.log(`[Webview] ${e.message}`);
        });
        
        // 启用webview通信以捕获postMessage
        webview.addEventListener('ipc-message', (e) => {
          console.log('收到IPC消息:', e.channel, e.args);
          
          // 处理openExternal消息，使用系统默认浏览器打开外部链接
          if (e.channel === 'openExternal' && e.args && e.args[0] && e.args[0].url) {
            console.log('打开外部链接:', e.args[0].url);
            window.electronAPI.openExternal(e.args[0].url);
          }
          
          // 处理createNewTab消息，改为在当前webview中加载
          if (e.channel === 'createNewTab' && e.args && e.args[0] && e.args[0].url) {
            webview.src = e.args[0].url;
          }
        });
      }
      
      // 如果electronAPI可用，处理URL加载消息
      if (window.electronAPI && window.electronAPI.createNewTab) {
        // 通过IPC接收create-new-tab事件
        window.electronAPI.createNewTab((url) => {
          console.log('通过IPC接收到URL加载请求:', url);
          if (mainWebview) {
            mainWebview.src = url;
          }
        });
      }

      // 版本更新检查
      document.getElementById('update-btn').addEventListener('click', async () => {
        // 添加loading状态
        const updateBtn = document.getElementById('update-btn');
        updateBtn.classList.add('loading');
        
        try {
          const result = await window.electronAPI.checkForUpdates();
          console.log('检查更新结果:', result);
          
          // 如果没有更新，会自动显示提示
          if (result.hasUpdate) {
            console.log('有新版本:', result.updateInfo);
          }
        } catch (error) {
          console.error('检查更新失败:', error);
        } finally {
          // 移除loading状态
          updateBtn.classList.remove('loading');
        }
      });
      
      // 添加确认更新按钮事件
      document.getElementById('update-confirm-btn').addEventListener('click', async () => {
        console.log('用户点击了立即更新按钮');
        try {
          // 调用确认更新API
          const result = await window.electronAPI.confirmUpdate();
          console.log('确认更新结果:', result);
        } catch (error) {
          console.error('确认更新时出错:', error);
        }
      });
      
      // 添加稍后更新按钮事件
      document.getElementById('update-later-btn').addEventListener('click', () => {
        console.log('用户点击了稍后更新按钮');
        // 隐藏更新覆盖层
        hideUpdateOverlay();
      });
      
      // 监听正在检查更新事件
      window.electronAPI.onUpdateChecking(() => {
        console.log('正在检查更新');
        
        // 显示检查更新提示覆盖层
        showUpdateStatusOverlay('正在检查更新...', '请稍候，正在连接服务器检查更新');
        
        // 添加loading状态到更新按钮
        const updateBtn = document.getElementById('update-btn');
        if (updateBtn) {
          updateBtn.classList.add('loading');
        }
      });
      
      // 监听更新可用事件
      window.electronAPI.onUpdateAvailable((updateInfo) => {
        console.log('发现新版本:', updateInfo);
        
        // 更新覆盖层状态
        updateOverlayStatus('发现新版本', `发现新版本 ${updateInfo.version}，是否现在更新？`);
        
        // 显示更新按钮
        const updateBtn = document.getElementById('update-btn');
        if (updateBtn) {
          updateBtn.style.display = 'block';
          updateBtn.classList.remove('loading');
        }
        
        // 显示更新按钮和稍后更新按钮
        const updateNowBtn = document.getElementById('update-now-btn');
        const updateLaterBtn = document.getElementById('update-later-btn');
        if (updateNowBtn) updateNowBtn.style.display = 'block';
        if (updateLaterBtn) updateLaterBtn.style.display = 'block';
        
        // 确保覆盖层是可见的
        const overlay = document.getElementById('update-progress-overlay');
        if (overlay && overlay.style.display !== 'flex') {
          overlay.style.display = 'flex';
          overlay.style.opacity = '1';
        }
      });

      // 监听没有可用更新事件
      window.electronAPI.onUpdateNotAvailable(() => {
        console.log('没有可用更新');
        
        // 更新覆盖层状态
        updateOverlayStatus('已是最新版本', '您当前使用的已经是最新版本');
        
        // 确保覆盖层是可见的
        const overlay = document.getElementById('update-progress-overlay');
        if (overlay && overlay.style.display !== 'flex') {
          overlay.style.display = 'flex';
          overlay.style.opacity = '1';
        }
        
        // 隐藏更新按钮
        const updateBtn = document.getElementById('update-btn');
        if (updateBtn) {
          updateBtn.style.display = 'none';
        }
        
        // 3秒后隐藏覆盖层
        setTimeout(hideUpdateOverlay, 2000);
      });
      
      // 新的显示更新状态覆盖层的工具函数
      function showUpdateStatusOverlay(title, message) {
        const overlay = document.getElementById('update-progress-overlay');
        if (!overlay) return;
        
        // 显示覆盖层
        overlay.style.display = 'flex';
        
        // 触发动画效果
        setTimeout(() => {
          overlay.style.opacity = '1';
        }, 10);
        
        // 更新标题
        const titleElem = document.getElementById('update-title');
        if (titleElem) {
          titleElem.textContent = title;
        }
        
        // 更新状态文本
        const status = document.getElementById('update-status');
        if (status) {
          status.textContent = message;
        }
        
        // 重置进度条
        const progressBarInner = document.getElementById('progress-bar-inner');
        if (progressBarInner) {
          progressBarInner.style.width = '0%';
        }
      }
      
      // 新的更新覆盖层状态函数
      function updateOverlayStatus(title, message) {
        const titleElem = document.getElementById('update-title');
        if (titleElem) {
          titleElem.textContent = title;
        }
        
        const status = document.getElementById('update-status');
        if (status) {
          status.textContent = message;
        }
      }
      
      // 新的隐藏更新覆盖层函数
      function hideUpdateOverlay() {
        const overlay = document.getElementById('update-progress-overlay');
        if (overlay) {
          // 添加淡出效果
          overlay.style.opacity = '0';
          
          // 等待过渡动画完成后隐藏元素
          setTimeout(() => {
            overlay.style.display = 'none';
          }, 300);
        }
      }
      
      // 监听开始下载更新事件
      window.electronAPI.onUpdateDownloadStart((updateInfo) => {
        console.log('开始下载更新:', updateInfo);
        
        // 显示更新进度覆盖层
        const overlay = document.getElementById('update-progress-overlay');
        if (overlay) {
          overlay.style.display = 'flex';
          setTimeout(() => {
            overlay.style.opacity = '1';
          }, 10);
          
          // 更新标题
          const title = document.getElementById('update-title');
          if (title) {
            title.textContent = `正在下载更新 v${updateInfo.versionName || updateInfo.version}...`;
          }
          
          // 显示进度条容器，隐藏按钮
          const progressContainer = document.getElementById('progress-container');
          if (progressContainer) {
            progressContainer.style.display = 'block';
          }
          
          const updateButtons = document.getElementById('update-buttons');
          if (updateButtons) {
            updateButtons.style.display = 'none';
          }
          
          // 重置进度条
          const progressBarInner = document.getElementById('progress-bar-inner');
          if (progressBarInner) {
            progressBarInner.style.width = '0%';
          }
          
          // 重置状态文本
          const progressText = document.getElementById('progress-text');
          if (progressText) {
            progressText.textContent = '准备下载...';
          }
        }
      });
      
      // 监听下载进度事件
      window.electronAPI.onUpdateDownloadProgress((progress) => {
        // 更新隐藏的原始进度条（保持功能兼容性）
        const progressBar = document.getElementById('update-progress-bar');
        if (progressBar) {
          progressBar.value = progress.percent;
        }
        
        // 更新可视化进度条
        const progressBarInner = document.getElementById('progress-bar-inner');
        if (progressBarInner) {
          progressBarInner.style.width = `${progress.percent}%`;
        }
        
        // 更新状态文本
        const progressText = document.getElementById('progress-text');
        if (progressText) {
          const percent = Math.round(progress.percent);
          const downloaded = Math.round(progress.transferred / 1024 / 1024 * 100) / 100;
          const total = Math.round(progress.total / 1024 / 1024 * 100) / 100;
          
          progressText.textContent = `已下载 ${percent}% (${downloaded} MB / ${total} MB)`;
        }
      });
      
      // 监听下载完成事件
      window.electronAPI.onUpdateDownloadCompleted(() => {
        // 隐藏更新进度覆盖层
        hideUpdateOverlay();
      });
      
      // 监听下载错误事件
      window.electronAPI.onUpdateDownloadError((errorData) => {
        console.error('下载更新出错:', errorData);
        
        // 更新进度条状态
        const title = document.getElementById('update-title');
        if (title) {
          title.textContent = '更新下载失败';
        }
        
        const status = document.getElementById('update-status');
        if (status) {
          status.textContent = `错误: ${errorData.error}`;
        }
        
        // 3秒后隐藏覆盖层
        setTimeout(hideUpdateOverlay, 3000);
      });
      
      // 页面加载后
      window.addEventListener('DOMContentLoaded', async () => {
        try {
          // 获取当前应用版本
          const version = await window.electronAPI.getAppVersion();
          console.log('当前应用版本:', version);
          
          // 添加版本号到标题
          const title = document.querySelector('.title');
          title.textContent = `管理系统 v${version}`;
        } catch (error) {
          console.error('获取版本失败:', error);
        }
        
        // 注册自定义对话框处理器
        if (window.electronAPI && window.electronAPI.onShowCustomDialog) {
          window.electronAPI.onShowCustomDialog((options) => {
            showCustomDialog(options);
          });
        }
      });
      
      // 显示自定义对话框
      function showCustomDialog(options) {
        const dialogOverlay = document.getElementById('custom-dialog-overlay');
        const dialogTitle = document.getElementById('dialog-title');
        const dialogMessage = document.getElementById('dialog-message');
        const dialogIcon = document.getElementById('dialog-icon');
        const dialogButtons = document.getElementById('dialog-buttons');
        
        if (!dialogOverlay || !dialogTitle || !dialogMessage || !dialogIcon || !dialogButtons) {
          console.error('对话框元素不存在');
          return;
        }
        
        // 设置标题和消息
        dialogTitle.textContent = options.title || '提示';
        dialogMessage.textContent = options.message || '';
        
        // 根据类型设置图标
        let iconBackground = 'linear-gradient(135deg, #4776e6, #8e54e9)';
        let iconSvg = '';
        
        switch (options.type) {
          case 'info':
            iconBackground = 'linear-gradient(135deg, #4776e6, #8e54e9)';
            iconSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10"></circle>
              <line x1="12" y1="16" x2="12" y2="12"></line>
              <line x1="12" y1="8" x2="12.01" y2="8"></line>
            </svg>`;
            break;
          case 'warning':
            iconBackground = 'linear-gradient(135deg, #ff9a00, #ff6a00)';
            iconSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
              <line x1="12" y1="9" x2="12" y2="13"></line>
              <line x1="12" y1="17" x2="12.01" y2="17"></line>
            </svg>`;
            break;
          case 'error':
            iconBackground = 'linear-gradient(135deg, #ff416c, #ff4b2b)';
            iconSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10"></circle>
              <line x1="15" y1="9" x2="9" y2="15"></line>
              <line x1="9" y1="9" x2="15" y2="15"></line>
            </svg>`;
            break;
          default:
            iconBackground = 'linear-gradient(135deg, #4776e6, #8e54e9)';
            iconSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10"></circle>
              <line x1="12" y1="16" x2="12" y2="12"></line>
              <line x1="12" y1="8" x2="12.01" y2="8"></line>
            </svg>`;
        }
        
        // 设置图标
        dialogIcon.style.background = iconBackground;
        dialogIcon.innerHTML = iconSvg;
        
        // 清除现有按钮
        dialogButtons.innerHTML = '';
        
        // 添加新按钮
        if (options.buttons && options.buttons.length > 0) {
          options.buttons.forEach((buttonText, index) => {
            const button = document.createElement('button');
            button.textContent = buttonText;
            
            // 设置按钮样式
            const isPrimary = index === (options.defaultId || 0);
            if (isPrimary) {
              button.style.cssText = `
                background: linear-gradient(90deg, #4776e6, #8e54e9);
                border: none;
                color: white;
                padding: 10px 20px;
                border-radius: 6px;
                font-size: 15px;
                cursor: pointer;
                transition: all 0.2s;
                margin: 0 6px;
              `;
            } else {
              button.style.cssText = `
                background: rgba(255, 255, 255, 0.1);
                border: 1px solid rgba(255, 255, 255, 0.2);
                color: white;
                padding: 10px 20px;
                border-radius: 6px;
                font-size: 15px;
                cursor: pointer;
                transition: all 0.2s;
                margin: 0 6px;
              `;
            }
            
            // 添加点击事件
            button.addEventListener('click', () => {
              hideCustomDialog();
              if (window.electronAPI && window.electronAPI.sendDialogResponse) {
                window.electronAPI.sendDialogResponse(options.id, index);
              }
            });
            
            dialogButtons.appendChild(button);
          });
        }
        
        // 显示对话框
        dialogOverlay.style.display = 'flex';
        setTimeout(() => {
          dialogOverlay.style.opacity = '1';
          
          // 添加键盘事件处理
          document.addEventListener('keydown', handleDialogKeyDown);
        }, 10);
      }
      
      // 隐藏自定义对话框
      function hideCustomDialog() {
        const dialogOverlay = document.getElementById('custom-dialog-overlay');
        if (dialogOverlay) {
          dialogOverlay.style.opacity = '0';
          
          // 移除键盘事件处理
          document.removeEventListener('keydown', handleDialogKeyDown);
          
          setTimeout(() => {
            dialogOverlay.style.display = 'none';
          }, 300);
        }
      }
      
      // 处理对话框键盘事件
      function handleDialogKeyDown(event) {
        // 按Escape键关闭对话框（相当于点击取消按钮）
        if (event.key === 'Escape') {
          const dialogOverlay = document.getElementById('custom-dialog-overlay');
          if (dialogOverlay && dialogOverlay.style.display !== 'none') {
            const buttons = document.querySelectorAll('#dialog-buttons button');
            const cancelIndex = buttons.length - 1;
            if (cancelIndex >= 0) {
              buttons[cancelIndex].click();
            }
          }
        }
        
        // 按Enter键确认（相当于点击确定按钮）
        if (event.key === 'Enter') {
          const dialogOverlay = document.getElementById('custom-dialog-overlay');
          if (dialogOverlay && dialogOverlay.style.display !== 'none') {
            const buttons = document.querySelectorAll('#dialog-buttons button');
            if (buttons.length > 0) {
              buttons[0].click();
            }
          }
        }
      }

      // 创建toast通知容器
      function createToastContainer() {
        let container = document.getElementById('toast-container');
        // 如果容器不存在才创建新的
        if (!container) {
          container = document.createElement('div');
          container.id = 'toast-container';
          container.className = 'toast-container';
          document.body.appendChild(container);
          console.log('创建了新的toast容器');
        }
        return container;
      }
      
      // 显示toast通知
      function showToast(message, type = 'info', duration = 3000) {
        const container = createToastContainer();
        
        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        
        // 图标
        let iconSvg = '';
        switch (type) {
          case 'success':
            iconSvg = '<svg width="20" height="20" viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="currentColor"/></svg>';
            break;
          case 'error':
            iconSvg = '<svg width="20" height="20" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z" fill="currentColor"/></svg>';
            break;
          case 'warning':
            iconSvg = '<svg width="20" height="20" viewBox="0 0 24 24"><path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z" fill="currentColor"/></svg>';
            break;
          case 'info':
          default:
            iconSvg = '<svg width="20" height="20" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z" fill="currentColor"/></svg>';
        }
        
        // 构造toast内容
        toast.innerHTML = `
          <div class="toast-icon">${iconSvg}</div>
          <div class="toast-content">${message}</div>
          <div class="toast-close">
            <svg width="16" height="16" viewBox="0 0 24 24">
              <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z" fill="currentColor"/>
            </svg>
          </div>
          ${duration > 0 ? '<div class="toast-progress" style="width: 100%"></div>' : ''}
        `;
        
        // 添加到容器
        container.appendChild(toast);
        
        // 绑定关闭按钮事件
        const closeBtn = toast.querySelector('.toast-close');
        closeBtn.addEventListener('click', () => {
          closeToast(toast);
        });
        
        // 自动关闭
        const toastId = Date.now();
        toast.dataset.id = toastId;
        
        if (duration > 0) {
          // 添加进度条动画
          const progress = toast.querySelector('.toast-progress');
          if (progress) {
            progress.style.transition = `width ${duration}ms linear`;
            // 触发reflow以确保动画可以立即开始
            progress.getBoundingClientRect();
            progress.style.width = '0';
          }
          
          setTimeout(() => {
            // 检查toast是否仍然存在
            const currentToast = document.querySelector(`.toast[data-id="${toastId}"]`);
            if (currentToast) {
              closeToast(currentToast);
            }
          }, duration);
        }
        
        return toastId;
      }
      
      // 关闭toast
      function closeToast(toast) {
        toast.classList.add('toast-out');
        toast.addEventListener('animationend', () => {
          if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
          }
        });
      }
      
      // 关闭特定ID的toast
      function closeToastById(id) {
        const toast = document.querySelector(`.toast[data-id="${id}"]`);
        if (toast) {
          closeToast(toast);
        }
      }
      
      // 关闭所有toast
      function closeAllToasts() {
        const toasts = document.querySelectorAll('.toast');
        toasts.forEach(toast => {
          closeToast(toast);
        });
      }
    </script>

    <!-- 键盘快捷键处理 -->
    <script>
      // 页面加载完成后设置键盘快捷键
      window.addEventListener('load', function() {
        // 添加键盘快捷键监听
        window.addEventListener('keydown', function(e) {
          console.log('全局键盘事件:', e.key, 'Alt:', e.altKey, 'Ctrl:', e.ctrlKey, 'Shift:', e.shiftKey);
          
          // 当Alt+Q按下时切换窗口显示/隐藏（首选快捷键）
          if ((e.key === 'q' || e.key === 'Q') && e.altKey && !e.ctrlKey && !e.shiftKey) {
            console.log('检测到Alt+Q快捷键');
            if (window.electronAPI && window.electronAPI.toggleWindowVisibility) {
              window.electronAPI.toggleWindowVisibility();
            }
          }
          
          // 当Alt+X按下时切换窗口显示/隐藏（备用快捷键，防止系统级快捷键冲突）
          if ((e.key === 'x' || e.key === 'X') && e.altKey && !e.ctrlKey && !e.shiftKey) {
            console.log('检测到Alt+X快捷键');
            if (window.electronAPI && window.electronAPI.toggleWindowVisibility) {
              window.electronAPI.toggleWindowVisibility();
            }
          }
          
          // F12切换窗口（额外备用）
          if (e.key === 'F12') {
            console.log('检测到F12快捷键');
            if (window.electronAPI && window.electronAPI.toggleWindowVisibility) {
              window.electronAPI.toggleWindowVisibility();
            }
          }
        });
        
        // 显示当前注册的快捷键
        if (window.electronAPI && window.electronAPI.getRegisteredHotkey) {
          window.electronAPI.getRegisteredHotkey()
            .then(hotkey => {
              console.log('检测到已注册的快捷键:', hotkey);
              const titleElement = document.querySelector('.title');
              if (titleElement) {
                const originalText = titleElement.textContent;
                titleElement.textContent = originalText + ' (快捷键: ' + hotkey + ')';
                titleElement.setAttribute('title', `使用 ${hotkey} 快速显示/隐藏窗口`);
              }
            })
            .catch(err => {
              console.error('获取快捷键信息失败:', err);
            });
        }
      });
    </script>
  </body>
</html>
